package cn.xuqiudong.backend.config;

import cn.xuqiudong.backend.config.properties.PathPrefixProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;

/**
 * 描述:
 * 修改一些全局配置
 *
 * @author Vic.xu
 * @since 2025-02-11 9:12
 */
@Configuration
@EnableConfigurationProperties(value = {PathPrefixProperties.class})
public class WebMvcConfig implements WebMvcConfigurer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfig.class);

    private PathPrefixProperties pathPrefixProperties;

    @Autowired
    public void setPathPrefixProperties(PathPrefixProperties pathPrefixProperties) {
        this.pathPrefixProperties = pathPrefixProperties;
    }

    /**
     * Configure a path prefix to apply to matching controller methods.
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // 为每个配置的包添加特定前缀
        Map<String, String> prefixMapping = pathPrefixProperties.getPrefixMapping();
        if (prefixMapping != null) {
            for (Map.Entry<String, String> entry : prefixMapping.entrySet()) {
                String packageName = entry.getKey();
                String prefix = entry.getValue();
                LOGGER.info("Add path prefix {} for package {}", prefix, packageName);
                configurer.addPathPrefix(prefix, c ->
                        (c.isAnnotationPresent(RestController.class) || c.isAnnotationPresent(Controller.class))
                                && c.getPackage() != null
                                && c.getPackage().getName().startsWith(packageName)
                );
            }
        }
        // 为没有匹配到特定前缀的控制器添加默认前缀
        String defaultPrefix = pathPrefixProperties.getDefaulted();
        if (defaultPrefix != null && !defaultPrefix.isEmpty()) {
            LOGGER.info("Add default path prefix {} for all controllers", defaultPrefix);
            configurer.addPathPrefix(defaultPrefix, c ->
                    (c.isAnnotationPresent(RestController.class) || c.isAnnotationPresent(Controller.class))
                            && (prefixMapping == null || prefixMapping.keySet().stream()
                            .noneMatch(packageName -> c.getPackage() != null
                                    && c.getPackage().getName().startsWith(packageName)))
            );
        }
    }


}
